﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using DAL;

namespace CTRL
{
    public sealed class CtrlCar
    {
        private static volatile CtrlCar instance;
        private static object syncRoot = new Object();

        private IDALCar carRepo;

        public CtrlCar()
        {
            this.carRepo = new DALCar(new CarBatteryEntities());
        }

        public static CtrlCar Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new CtrlCar();
                    }
                }

                return instance;
            }
        }

        public int CreateCar(double range, double capacity, int _customerID, string _licencePlate)
        {
            CtrlCustomer custCtrl = CtrlCustomer.Instance;

            if (custCtrl.GetCustomer(_customerID) != null)
                carRepo.InsertCar(new Car() { range = range, capacity = capacity, customerID = _customerID, licencePlate = _licencePlate });

            return carRepo.Save();
        }

        public int UpdateCar(int ID, double range, double capacity, int _customerID, string _licencePlate)
        {
            CtrlCustomer custCtrl = CtrlCustomer.Instance;
            Car car = GetCar(ID);

            if ((custCtrl.GetCustomer(_customerID) != null) && (car != null))
            {
                car.range = range;
                car.capacity = capacity;
                car.customerID = _customerID;
                car.licencePlate = _licencePlate;
            }

            return carRepo.Save();
        }

        public int DeleteCar(int ID)
        {
            Car car = GetCar(ID);

            if (car != null)
                carRepo.DeleteCar(ID);

            return carRepo.Save();
        }

        public IEnumerable<Car> GetAllCarsOwnedByCustomer(int customerID)
        {
            return carRepo.GetAllCarsOwnedByCustomer(customerID);
        }

        public Car GetCar(int carID)
        {
            return carRepo.GetCarByID(carID);
        }

        public Car FindCarByLicencePlate(string licencePlate)
        {
            return carRepo.FindCarByLicencePlate(licencePlate);
        }

        public int DeleteCarsOwnedByCustomer(int customerID)
        {
            IEnumerable<Car> cars = GetAllCarsOwnedByCustomer(customerID);

            foreach (Car _car in cars)
                DeleteCar(_car.carID);

            return carRepo.Save();
        }
    }
}